//
//  CCSManager.swift
//  HHSwift
//
//  Created by 华宏 on 2019/10/15.
//  Copyright © 2019 huahong. All rights reserved.
//

import Foundation
import Alamofire
import HandyJSON

class CCSManager {
    

    var resultDic:NSDictionary? = nil
    
    typealias CallBack = (_ response:[CityModel]) -> ()
       
    fileprivate  let urlStr = "http://58.215.175.244:8090/thirdprovider/datacenter/area/findAllAreaJsonTree"

       static let shared = CCSManager()
       private init() {
           
       }
       
       
    func getCityCompanyServiceData(complate: @escaping((_ response:NSDictionary) -> ()),errorBlock: @escaping(() -> ())) {
           
           
            if self.resultDic != nil {
                complate(self.resultDic!)
              return
            }
           
           //1284
           Alamofire.request(urlStr, method: .post, parameters: ["userId":""],encoding: JSONEncoding.default).responseJSON { (response) in


                 switch response.result{
                     case .success(_):

                        guard let dict = response.result.value as? NSDictionary else{
                            
                            self.resultDic = nil
                            return  errorBlock()
                            
                        }
                   
                        self.resultDic = dict
                        complate(self.resultDic!)
                    

                 case .failure(let error):
                     print("response error: \(error)")
                    errorBlock()
                 }

             }
          
       }
    
    
    func getCityModelList(callBack: @escaping(CallBack)) {
       
        var dataArray:[CityModel] = []

        getCityCompanyServiceData(complate: { (data) in
           
         guard let result = data as? [String:AnyObject] else { return callBack([]) }
            
          let dataList:Array = result["data"] as? Array<Any> ?? []
          for dict in dataList {
              
        guard let cityModel = CityModel.deserialize(from: dict as? [String:Any]) else { return }
          
            dataArray.append(cityModel)
              
          }
        
        callBack(dataArray)
                                 
          
            
        }) {
          callBack([])
        }
        
         
    }
}
